//
//  HistoryApplySearchViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-9-10.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "HistoryApplySearchViewController.h"
#import "ApplyErandsViewController.h"
#import "CommonDatePickerViewController.h"

@interface HistoryApplySearchViewController () <CommonDatePickerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *searchContentView;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UILabel *beginDateLbl;
@property (weak, nonatomic) IBOutlet UILabel *endDateLbl;

@property (nonatomic, strong) NSString *startTime;
@property (nonatomic, strong) NSString *endTime;
@property (nonatomic ,strong) NSMutableArray *applyList; //出差申请列表

@property (nonatomic, strong) CommonDatePickerViewController *datePicker;
@property (nonatomic, assign) int dateType; //1表示起始时间，2表示结束时间

- (IBAction)searchErandAction:(id)sender;
- (IBAction)selectDateAction:(id)sender;

@end

@implementation HistoryApplySearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.networkManager = [[NetworkManager alloc] init];
    self.applyList = [NSMutableArray array];
    [self initHUD];
    
    [self searchErandAction:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    
    self.title = @"历史出差查询";
    [super viewWillAppear:animated];
    
    [self searchErandAction:nil];
}

- (void)refreshViewByReloadData {
    [self searchErandAction:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

//获取历史出差列表
- (void)getHistoryErandsApplyListFrom:(NSString *)startDate to:(NSString *)endDate {
    if (!self.isRefreshing) {
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                      gonghao,@"gh", nil];
        if ([startDate length] > 0) {
            [param setValue:startDate forKey:@"startTime"];
        }
        if ([endDate length] > 0) {
            [param setValue:endDate forKey:@"endTime"];
        }
        [self.networkManager requestWithMethod:showProjectIfComplete parameter:param delegate:self];
        [self.HUD show:YES];
        
        self.isRefreshing = YES;
    }
}

- (IBAction)searchErandAction:(id)sender {
    NSString *startDate = self.beginDateLbl.text;
    NSString *endDate = self.endDateLbl.text;
    if ([startDate length] == 0 || [startDate isEqualToString:@"起始时间"]) {
        startDate = @"";
    }
    
    if ([endDate length] == 0 || [endDate isEqualToString:@"结束时间"]) {
        endDate = @"";
    }
    
    self.startTime = startDate;
    self.endTime = endDate;
    
    [self getHistoryErandsApplyListFrom:startDate to:endDate];
}

- (IBAction)selectDateAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    self.datePicker = (CommonDatePickerViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CommonDatePicker"];
    _datePicker.delegate = self;
    _datePicker.view.tag = tag;
    
    AppDelegate *app = [AppDelegate sharedDelegate];
    _datePicker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame),
                                        CGRectGetHeight(self.view.bounds));
    
    [app.window addSubview:_datePicker.view];
}

#pragma mark - CommonDatePickerDelegate
- (void)picker:(CommonDatePickerViewController *)picker didSelectedDate:(NSDate *)date {
    if (date != nil) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [formatter stringFromDate:date];
        
        NSInteger tag = picker.view.tag;
        if (tag == 100) { //起始时间
            self.beginDateLbl.text = strDate;
        } else if (tag == 101) {
            self.endDateLbl.text = strDate;
        }
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) { //请求成功
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                
                if (methodId == showProjectIfComplete) { //历史出差列表
                    [self.applyList removeAllObjects];
                    
                    if ([dataObject isKindOfClass:[NSArray class]]) {
                        self.applyList = [NSMutableArray arrayWithArray:dataObject];
                    }
                    
                    [self.tableView reloadData];
                    
                }
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"历史出差查询失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.applyList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsApplyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    NSLog(@"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    UILabel *userNameLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *userIDLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *agencyNameLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *agencyCodeLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *reasonLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:107];
    
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *merchantName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *merchantCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *time = [cellData objectForKeyOrNil:@"ccsj"];
        if ([dudaoName isKindOfClass:[NSNull class]]) {
            dudaoName = @"";
        }
        if ([dudaoCode isKindOfClass:[NSNull class]]) {
            dudaoCode = @"";
        }
        if ([merchantName isKindOfClass:[NSNull class]]) {
            merchantName = @"";
        }
        if ([merchantCode isKindOfClass:[NSNull class]]) {
            merchantCode = @"";
        }
        if ([reason isKindOfClass:[NSNull class]]) {
            reason = @"";
        }
        if ([time isKindOfClass:[NSNull class]]) {
            time = @"";
        }
        
        userNameLbl.text = dudaoName;
        userIDLbl.text = dudaoCode;
        agencyNameLbl.text = merchantName;
        agencyCodeLbl.text = merchantCode;
        reasonLbl.text = reason;
        dateLbl.text = time;
        
        BOOL rejected = [[cellData objectForKeyOrNil:@"sfbh"] boolValue]; //是否驳回
        BOOL passed = [[cellData objectForKeyOrNil:@"shzt"] boolValue]; //申请状态
        BOOL submitted = [[cellData objectForKey:@"sftj"] boolValue]; //是否已经提交
        
        if (rejected) {
            [statusBtn setTitle:@"驳回" forState:UIControlStateNormal];
            [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
            [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_驳回.png"] forState:UIControlStateNormal];
        } else {
            if (passed) { //通过
                [statusBtn setTitle:@"完成" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
            } else if (submitted) { //待审核
                [statusBtn setTitle:@"待审核" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_通过.png"] forState:UIControlStateNormal];
            } else { //未通过
                [statusBtn setTitle:@"未通过" forState:UIControlStateNormal];
                [statusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [statusBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
                [statusBtn setBackgroundImage:[UIImage imageNamed:@"tip_未通过.png"] forState:UIControlStateNormal];
            }
        }
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"@@@@222222222");
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        ApplyErandsViewController *applyVC = (ApplyErandsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ApplyErandsViewController"];
        applyVC.erandInfo = [NSMutableDictionary dictionaryWithDictionary:cellData];
        applyVC.canEdit = NO;
        [self.navigationController pushViewController:applyVC animated:YES];
    }
}

@end
